﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
//using PCSUtils.Utils;
//using PCSComUtils.Common;
using PCSComProduct.Items.BO;
using PCSComUtils.DataContext;
using PCSComUtils.Common.DS;

using C1.Win.C1Input;
using C1.Win.C1TrueDBGrid;
using PCSComUtils.Common;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
using CancelEventArgs = System.ComponentModel.CancelEventArgs;
namespace PCSProduct.Items
{
    public partial class Value_for_working_time : Form
    {
        DataSet dset;
        System.Data.OleDb.OleDbConnection oconExcelFile = new System.Data.OleDb.OleDbConnection();
        System.Data.OleDb.OleDbCommand ocmdExcelSelect = new OleDbCommand();
        bool iCheckCopy = false;
        string strNewFile = string.Empty;

        private string strExcelFilename = "";
        private ExcelReader objExcelReader = null;
        private DataTable dtbData;
        private System.Windows.Forms.TextBox txtShiftCode;
        private System.Windows.Forms.Button btnShiftCode;
        private System.Windows.Forms.Label lblShiftCode;
        private DataTable dtbGridLayout = new DataTable();

        #region Properies
        //private readonly PartyBO boParty = new PartyBO();
        private EnumAction mFormAction = EnumAction.Default;
        const string THIS = "PCSProduct.Items.Value_for_working_time";
        public EnumAction FormAction
        {
            set { mFormAction = value; }
            get { return mFormAction; }
        }
        string METHOD_NAME = string.Empty;
        List<ItemVO> _items = new List<ItemVO>();
        //DataSet dset;
        //System.Data.DataTable dtbGridLayout;

        private MST_Party voParty = new MST_Party();
        private int iPartyID = 0;
        DataRowView drResultRegoint = null;

        #endregion
        public Value_for_working_time()
        {
            InitializeComponent();
        }

        private void Value_for_working_time_Load(object sender, EventArgs e)
        {
            
            LoadReportType();
            btnSave.Enabled = false; btnDelete.Enabled = false; btnEdit.Enabled = false;
            btnCopy.Enabled = false;
            //cboReportType.Enabled = false;
        }
        //Load Combobox
        private void LoadReportType()
        {
            //_items.Add(new ColumnChartItem(Color.DarkBlue, "Column 2", 10.7m));
            _items.Add(new ItemVO(0, "Chuyển số liệu sang bảng AA"));
            _items.Add(new ItemVO(1, "Convert All"));
            _items.Add(new ItemVO(2, "S1: Import to ITM_PRODUCT"));

            _items.Add(new ItemVO(3, "S2: Import Routing")); // Ma HHNB
            _items.Add(new ItemVO(4, "S3: Update Item co duoi LVT, VCNB bang Vat lieu phu, ProductTypeID=3"));//NN_KHAC

            _items.Add(new ItemVO(5, "S4: Insert BOM"));
            _items.Add(new ItemVO(6, "S5: Insert BOM Nguyenvatlieu"));
            _items.Add(new ItemVO(7, "S6: BOM THEO LevelsS"));
            _items.Add(new ItemVO(8, "S7: Đổi chủng loại")); 


            //_items.Add(new ItemVO(4, "S3: Update Item co duoi LVT, VCNB bang Vat lieu phu, ProductTypeID=3"));//NN_KHAC

            if (cboReportType.Row == 0) // no contain data
            {
                if (_items.Count > 0)
                {
                    cboReportType.DataSource = _items;
                    cboReportType.ValueMember = "Values";

                    cboReportType.DisplayMember = "Description";
                }
            }
            //cboReportType.Va;
            cboReportType.SelectedIndex = -1;
            //cboReportType.Width = 300;
            cboReportType.Splits[0].DisplayColumns["Values"].Width = 50;
            cboReportType.Splits[0].DisplayColumns["Description"].Width = 250;
            
            //cboReportType.Text = "";
        }
        private string CorrectExcelFile(string pstrFileName)
        {
            const int START_ROW = 2;
            const int MAX_COL = 50;
            const int PARTNO_COL = 2;
            const int PARTNAME_COL = 3;
            const int START_COL_DATE = 7;
            const string DATE_TIME = "yyyyMMdd HHmmss";
            const string XLS = ".xls";
            const int INT_MAX_MONTH = 12;
            const string BLANK = " ";

            Microsoft.Office.Interop.Excel.Application objExcelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook objWorkBook = objExcelApp.Workbooks.Open(pstrFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            Microsoft.Office.Interop.Excel.Worksheet objSheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkBook.Worksheets.get_Item(2);
            //Microsoft.Office.Interop.Excel.Range objRange = objSheet.get_Range(objSheet.Cells[1,1],objSheet.Cells[50,50]);
            objExcelApp.Visible = false;
            objExcelApp.AlertBeforeOverwriting = false;
            objExcelApp.DisplayAlerts = false;
            objExcelApp.ScreenUpdating = false;
            Microsoft.Office.Interop.Excel.Range objRangeMonth = objSheet.get_Range(objSheet.Cells[1, 1], objSheet.Cells[1, 1]);
            string strValue = string.Empty;
            string strStoreMonthYear = string.Empty;
            int intMonth = 0, intYear = 0;
            if (objRangeMonth.Value2 != null)
            {
                objRangeMonth.ClearFormats();
                //Second, check title to get month
                string strMMYYYY = objRangeMonth.Value2.ToString();
                if (!strMMYYYY.Equals(string.Empty))
                {
                    const string DATE_SLASH = "/";
                    try
                    {
                        intMonth = int.Parse(strMMYYYY.Substring(0, strMMYYYY.IndexOf(DATE_SLASH)));
                        intYear = int.Parse(strMMYYYY.Substring(strMMYYYY.IndexOf(DATE_SLASH) + DATE_SLASH.Length));
                        strStoreMonthYear = BLANK + strMMYYYY;
                    }
                    catch
                    {
                        //Do nothing
                    }
                }
            }
            int[] delCols = new int[MAX_COL];
            // Modify date
            for (int intCol = START_COL_DATE; intCol < MAX_COL; intCol++)
            {
                Microsoft.Office.Interop.Excel.Range objRange = objSheet.get_Range(objSheet.Cells[START_ROW, intCol], objSheet.Cells[START_ROW, intCol]);

                if (objRange.Value2 != null)
                {
                 
                    objRange.ClearFormats();
                    strValue = objRange.Value2.ToString();
                    try
                    {
                        int intDay = Convert.ToInt16(strValue);
                        objRange.Value2 = intDay;
                        if (DateTime.DaysInMonth(intYear, intMonth) < intDay)
                        {
                            delCols[intCol] = intDay;
                        }
                    }
                    catch
                    {

                    }
                }
                else
                {
                    delCols[intCol] = 1;
                    continue;
                }
            }
            // del all redundal column
            for (int col = delCols.Length - 1; col > 0; col--)
            {
                if (delCols[col] > 0)
                {
                    Microsoft.Office.Interop.Excel.Range objRange = objSheet.get_Range(objSheet.Cells[START_ROW, col], objSheet.Cells[START_ROW, col]);
                    objRange.EntireColumn.Delete(false);
                }
            }

            Microsoft.Office.Interop.Excel.Range objRangeNo = objSheet.get_Range(objSheet.Cells[START_ROW, PARTNO_COL], objSheet.Cells[START_ROW, PARTNO_COL]).EntireColumn;
            objRangeNo.ClearFormats();
            // First column
            objRangeNo = objSheet.get_Range(objSheet.Cells[START_ROW, PARTNO_COL - 1], objSheet.Cells[START_ROW, PARTNO_COL - 1]).EntireColumn;
            objRangeNo.Value2 = string.Empty;
            objRangeMonth.Value2 = strStoreMonthYear;
            Microsoft.Office.Interop.Excel.Range objRangeName = objSheet.get_Range(objSheet.Cells[START_ROW, PARTNAME_COL], objSheet.Cells[START_ROW, PARTNAME_COL]).EntireColumn;
            objRangeName.ClearFormats();

            string strNewFile = pstrFileName + DateTime.Now.ToString(DATE_TIME) + XLS;
            objWorkBook.SaveCopyAs(strNewFile);
            objWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
            objExcelApp.Quit();
            return strNewFile;
        }
        private DataTable ReadImportData(string strFilename)
        {
            const string CONN_STR_TEMPL = "Provider=Microsoft.Jet.OLEDB.4.0;"
                                        + "Data Source = {0};"
                                        + "Extended Properties=\"Excel 8.0;Imex=2;HDR=No\"";
            const string CMD_STR_TEMPL = "Select * FROM [{0}$]"; //
            const int MAIN_SHEET_IDX = 0;
            const string SHEET_NAME_IDX = "TABLE_NAME";
            const string DOLLAR = "$";

            //const string METHOD_NAME = THIS + ".cboTransDate_DropDownClosed()";
            try
            {
                try
                {
                    strNewFile = CorrectExcelFile(strFilename);
                }
                catch
                {
                    strNewFile = strFilename;
                }
                //string strConnStr = string.Format(CONN_STR_TEMPL,strFilename);
                string strConnStr = string.Format(CONN_STR_TEMPL, strNewFile);
                DataTable dtSales = new DataTable();
                oconExcelFile.ConnectionString = strConnStr;
                try
                {
                    oconExcelFile.Open();
                }
                catch
                {
                    return null;
                }

                //Get sheetnames
                DataTable dtSChema = oconExcelFile.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (dtSChema.Rows.Count <= MAIN_SHEET_IDX)
                {
                    return null;
                }
                string strSheetName = dtSChema.Rows[MAIN_SHEET_IDX][SHEET_NAME_IDX].ToString();
                if (strSheetName.EndsWith("'"))
                    strSheetName = strSheetName.Substring(1, strSheetName.Length - 2);
                if (strSheetName.EndsWith(DOLLAR))
                {
                    strSheetName = strSheetName.Substring(0, strSheetName.Length - 1);
                }
                string strCmdSelect = string.Format(CMD_STR_TEMPL, strSheetName);
                ocmdExcelSelect.CommandText = strCmdSelect;

                //Fill table                
                OleDbDataAdapter oleAdapter = new OleDbDataAdapter(strCmdSelect, oconExcelFile);
                oleAdapter.Fill(dtSales);

                return dtSales;
            }
            catch (Exception ex)
            {
                //throw ex;
                return null;
            }
            finally
            {
                if (oconExcelFile.State != ConnectionState.Closed)
                {
                    oconExcelFile.Close();
                    if (strNewFile != strFilename)
                    {
                        System.IO.File.Delete(strNewFile);
                    }
                }
            }
        }
        private void btnImport_Click(object sender, EventArgs e)
        {
            ////try
            ////{
            //    //Do Import
            //    if (dlgOpenImpFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //    {
            //        DataTable dt = ReadImportData(dlgOpenImpFile.FileName);
            //        if (dt == null)
            //        {
            //            //Invalid file
            //            PCSMessageBox.Show(ErrorCode.MESSAGE_IMPORT_ERROR_READ_FILE, MessageBoxIcon.Error);
            //            return;
            //        }

            //        int iCol = -1, iRow = -1;

            //        if (iCol > -1)
            //        { HighlightExcelFile(iRow, iCol, dlgOpenImpFile.FileName); return; }

            //        dt.Rows[0].Delete();
            //        dt.AcceptChanges();
            //        ITM_ValueForWorkingTimeMaster objMaster = new ITM_ValueForWorkingTimeMaster();
            //        objMaster.MaHieu = dt.Rows[0][5] != null ? dt.Rows[0][5].ToString() : DateTime.Now.ToString();
            //        objMaster.TenSP = dt.Rows[0][4] != null ? dt.Rows[0][4].ToString() : DateTime.Now.ToString();
            //        dt.Rows[0].Delete();
            //        dt.AcceptChanges();
            //        List<ITM_ValueForWorkingTimeDetail> listDetail = new List<ITM_ValueForWorkingTimeDetail>();
            //        foreach (DataRow dr in dt.Rows)
            //        {
            //            ITM_ValueForWorkingTimeDetail objDetail = new ITM_ValueForWorkingTimeDetail();
            //            objDetail.MaSo = dr[1].ToString();
            //            objDetail.C1 = dr[2].ToString();
            //            objDetail.C2 = dr[3].ToString();
            //            objDetail.Name = dr[4] != null ? dr[4].ToString() : string.Empty;
            //            objDetail.Code = dr[5] != null ? dr[5].ToString() : string.Empty;


            //            if (dr[6] != null && dr[6].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.Levels = Convert.ToInt32(dr[6]);
            //                }
            //                catch { }
            //            if (dr[7] != null && dr[7].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.Parrent = Convert.ToInt32(dr[7]);
            //                }
            //                catch { }
                       
            //            objDetail.DVTP = dr[8].ToString();

            //            if (dr[9] != null && dr[9].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.Gqty = Convert.ToInt32(dr[9]);
            //                    //objDetail.SoLuong = Convert.ToInt32(dr[9]);
            //                }
            //                catch { }


            //            objDetail.TenQuyCachVatLieu = dr[11].ToString();
            //            objDetail.MaVTHH = dr[12].ToString();
                        
            //            objDetail.UM = dr[13] != null ? dr[13].ToString() : string.Empty;
                        
                      
            //            if (dr[14] != null && dr[14].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.Qty = Convert.ToDecimal(dr[14]);
            //                }
            //                catch { }
                       
                        
            //            if (dr[15] != null && dr[15].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.TrongLuong = Convert.ToDecimal(dr[15]);
            //                }
            //                catch { }
                        
                      
            //            if (dr[16] != null && dr[16].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.LinhVT = Convert.ToDecimal(dr[16]);
            //                }
            //                catch { }
                     
            //            if (dr[17] != null && dr[17].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m1 = Convert.ToDecimal(dr[17]);
            //                }
            //                catch { }
            //            if (dr[18] != null && dr[18].ToString() != string.Empty)
            //                try { objDetail.m2 = Convert.ToDecimal(dr[18]); }
            //                catch { }
            //            if (dr[19] != null && dr[19].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m3 = Convert.ToDecimal(dr[19]);
            //                }
            //                catch { }
            //            if (dr[20] != null && dr[20].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m4 = Convert.ToDecimal(dr[20]);
            //                }
            //                catch { }
            //            if (dr[21] != null && dr[21].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m5 = Convert.ToDecimal(dr[21]);
            //                }
            //                catch { }
            //            if (dr[22] != null && dr[22].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m6 = Convert.ToDecimal(dr[22]);
            //                }
            //                catch { }
            //            if (dr[23] != null && dr[23].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m7 = Convert.ToDecimal(dr[23]);
            //                }
            //                catch { }
            //            if (dr[24] != null && dr[24].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m8 = Convert.ToDecimal(dr[24]);
            //                }
            //                catch { }
            //            if (dr[25] != null && dr[25].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m9 = Convert.ToDecimal(dr[25]);
            //                }
            //                catch { }
            //            if (dr[26] != null && dr[26].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m10 = Convert.ToDecimal(dr[26]);
            //                }
            //                catch { }
            //            if (dr[27] != null && dr[27].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m11 = Convert.ToDecimal(dr[27]);
            //                }
            //                catch { }
            //            if (dr[28] != null && dr[28].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.m12 = Convert.ToDecimal(dr[28]);
            //                }
            //                catch { }
            //            if (dr[29] != null && dr[29].ToString() != string.Empty)
            //                try
            //                {
            //                    objDetail.Vc_NoiBo = Convert.ToDecimal(dr[29]);
            //                }
            //                catch { }
            //            objDetail.GhiChu = dr[30] != null ? dr[30].ToString() : string.Empty;
            //            listDetail.Add(objDetail);
            //        }
            //        ValueForWorkingTimeBO objBO = new ValueForWorkingTimeBO();
            //        if (objBO.Insert(objMaster, listDetail))
            //        {
            //            PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA, MessageBoxIcon.Information);
            //            //DataTable dtbGridDesign = FormControlComponents.StoreGridLayout(dgrdData);
            //            dset = objBO.GetData(objMaster.ValueForWorkingTimeMasterID);
            //            dgrdData.DataSource = dset.Tables[0];
            //            txtGoodsCode.Text = objMaster.MaHieu;
            //            txtGoodsName.Text = objMaster.TenSP;
            //            txtGoodsCode.Tag = objMaster.ValueForWorkingTimeMasterID;
            //            cboReportType.Enabled = true;
            //            //FormControlComponents.RestoreGridLayout(dgrdData, dtbGridLayout);
            //        }
            //        else
            //            PCSMessageBox.Show(ErrorCode.MESSAGE_CANNOT_SAVE_TO_DB, MessageBoxIcon.Error);
            //    }
            ////}
            ////catch (Exception)
            ////{
            ////    MessageBox.Show("File đầu vào có cấu trúc không hợp lệ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            ////    return;
            ////}
            const string METHOD_NAME = THIS + ".btnImport_Click()";
            try
            {
                Cursor = Cursors.WaitCursor;
                InitExcel(ref objExcelReader);
                dtbData = objExcelReader.GetTable("A1");
                dtbData.DefaultView.Sort = "F1";
                dgrdData.DataSource = dtbData;
                //c1TrueDBGrid1.DataSource = dtbData;
                FormControlComponents.RestoreGridLayout(dgrdData, dtbGridLayout);

                objExcelReader.Close();
                objExcelReader.Dispose();
                objExcelReader = null;
                Cursor = Cursors.Default;
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
                }
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        public void HighlightExcelFile(int intRow, int intMaxCol, string strFilename)
        {
            const int RED_COLOR = 3;

            Microsoft.Office.Interop.Excel.Application objExcelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook objWorkBook = objExcelApp.Workbooks.Open(strFilename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            try
            {
                #region HACK: DEL Trada 27-10-2005                
                Microsoft.Office.Interop.Excel.Worksheet objSheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkBook.Worksheets.get_Item(1);
                Microsoft.Office.Interop.Excel.Range objRange = objSheet.get_Range(objSheet.Cells[intRow + 1, 1], objSheet.Cells[intRow + 1, intMaxCol]);
                objRange.Interior.ColorIndex = RED_COLOR;

                objExcelApp.Visible = true;
                //objExcelApp.AlertBeforeOverwriting = false;
                //objExcelApp.DisplayAlerts = false;
                //objExcelApp.ScreenUpdating = false;

                //objWorkBook.Save();

                #endregion

            }
            catch
            {

            }
            finally
            {
                //objWorkBook.Close(Type.Missing,Type.Missing,Type.Missing);
                //objExcelApp.Quit();
            }
        }
        private void btnSelectCode_Click(object sender, EventArgs e)
        {
            DataRowView dresult = FormControlComponents.OpenSearchForm("ITM_ValueForWorkingTimeMaster", "TenSP", txtGoodsCode.Text.Trim(), null, true);
            if (dresult != null)
            {
                //              DataTable dtbGridDesign = FormControlComponents.StoreGridLayout(dgrdData);
                txtGoodsCode.Text = dresult["TenSP"].ToString();
                txtGoodsCode.Tag = dresult["ValueForWorkingTimeMasterID"];
                txtGoodsName.Text = dresult["MaHieu"].ToString();
                ValueForWorkingTimeBO objBO = new ValueForWorkingTimeBO();
                dset = objBO.GetData(Convert.ToInt32(txtGoodsCode.Tag));
                dgrdData.DataSource = dset.Tables[0];
                btnEdit.Enabled = true; btnDelete.Enabled = true; btnSave.Enabled = false;
                btnCopy.Enabled = true;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            PCSProduct.Items.ImportExel frm = new ImportExel();
            frm.Show();

            this.Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (txtGoodsCode.Tag != null)
            {
                DialogResult enumResult = PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD,
                                                             MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (enumResult == DialogResult.Yes)
                {
                    ValueForWorkingTimeBO objBO = new ValueForWorkingTimeBO();
                    objBO.Delete(Convert.ToInt32(txtGoodsCode.Tag));
                    txtGoodsCode.Tag = null; txtGoodsCode.Text = txtGoodsName.Text = string.Empty;
                    dgrdData.DataSource = null;
                }
            }
           
        }

        private void btnCheckItem_Click(object sender, EventArgs e)
        {
            ValueForWorkingTimeBO objBO = new ValueForWorkingTimeBO();
            DataSet dset = objBO.GetListKTMaVTHH();
            if (dset != null && dset.Tables.Count > 0)
            {
                string strCode = "";
                int idem = 0;
                foreach (DataRow dr in dset.Tables[0].Rows)
                {
                    if (idem > 0 && idem < dset.Tables[0].Rows.Count - 1)
                    {
                        strCode += "," + dr["MaVTHH"].ToString();
                    }
                    else
                    {
                        strCode += dr["MaVTHH"].ToString();
                    }
                }
                MessageBox.Show("MaVTHH đã có trong hệ thống: " + strCode, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                MessageBox.Show("Không có sản phẩm nào trong hệ thống","Thông báo",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void btnExport_Click(object sender, EventArgs e)
        {

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtGoodsCode.Text.Trim() == "")
            {
                MessageBox.Show("Mã thành phẩm không được bỏ trống","Thông báo",MessageBoxButtons.OK,MessageBoxIcon.Error);
                txtGoodsCode.Focus();
                return;
            }
            try
            {
                if (dset != null && dset.Tables.Count > 0)
                {
                    ITM_ValueForWorkingTimeMaster objMaster = new ITM_ValueForWorkingTimeMaster();
                    objMaster.MaHieu = txtGoodsCode.Text.Trim();
                    objMaster.TenSP = txtGoodsName.Text.Trim();

                    List<ITM_ValueForWorkingTimeDetail> listDetail = new List<ITM_ValueForWorkingTimeDetail>();
                    foreach (DataRow dr in dset.Tables[0].Rows)
                    {
                        ITM_ValueForWorkingTimeDetail objDetail = new ITM_ValueForWorkingTimeDetail();
                        objDetail.MaSo = dr["Mã số"].ToString();
                        objDetail.C1 = dr["Cụm#"].ToString();
                        objDetail.C2 = dr["Cụm#.#"].ToString();
                        objDetail.Name = dr["Tên chi tiết"] != null ? dr["Tên chi tiết"].ToString() : string.Empty;
                        objDetail.Code = dr["Ký hiệu"] != null ? dr["Ký hiệu"].ToString() : string.Empty;


                        if (dr["Levels"] != null && dr["Levels"].ToString() != string.Empty)
                            try
                            {
                                objDetail.Levels = Convert.ToInt32(dr["Levels"]);
                            }
                            catch { }
                        if (dr["Parrent"] != null && dr["Parrent"].ToString() != string.Empty)
                            try
                            {
                                objDetail.Parrent = dr["Parrent"].ToString();
                            }
                            catch { }

                        objDetail.DVTP = dr["DVTP"].ToString();

                        if (dr["Số lượng"] != null && dr["Số lượng"].ToString() != string.Empty)
                            try
                            {
                                objDetail.Gqty = Convert.ToInt32(dr["Số lượng"]);
                                //objDetail.SoLuong = Convert.ToInt32(dr[9]);
                            }
                            catch { }


                        objDetail.TenQuyCachVatLieu = dr["Tên quy cách vật liệu"].ToString();
                        objDetail.MaVTHH = dr["MaVTHH"].ToString();

                        objDetail.UM = dr["Đơn vị"] != null ? dr["Đơn vị"].ToString() : string.Empty;


                        if (dr["Slg VT"] != null && dr["Slg VT"].ToString() != string.Empty)
                            try
                            {
                                objDetail.Qty = Convert.ToDecimal(dr["Slg VT"]);
                            }
                            catch { }


                        if (dr["Trọng lượng"] != null && dr["Trọng lượng"].ToString() != string.Empty)
                            try
                            {
                                objDetail.TrongLuong = Convert.ToDecimal(dr["Trọng lượng"]);
                            }
                            catch { }


                        if (dr["LinhVT"] != null && dr["LinhVT"].ToString() != string.Empty)
                            try
                            {
                                objDetail.LinhVT = Convert.ToDecimal(dr["LinhVT"]);
                            }
                            catch { }

                        if (dr["m1"] != null && dr["m1"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m1 = Convert.ToDecimal(dr["m1"]);
                            }
                            catch { }
                        if (dr["m2"] != null && dr["m2"].ToString() != string.Empty)
                            try { objDetail.m2 = Convert.ToDecimal(dr["m2"]); }
                            catch { }
                        if (dr["m3"] != null && dr["m3"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m3 = Convert.ToDecimal(dr["m3"]);
                            }
                            catch { }
                        if (dr["m4"] != null && dr["m4"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m4 = Convert.ToDecimal(dr["m4"]);
                            }
                            catch { }
                        if (dr["m5"] != null && dr["m5"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m5 = Convert.ToDecimal(dr["m5"]);
                            }
                            catch { }
                        if (dr["m6"] != null && dr["m6"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m6 = Convert.ToDecimal(dr["m6"]);
                            }
                            catch { }
                        if (dr["m7"] != null && dr["m7"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m7 = Convert.ToDecimal(dr["m7"]);
                            }
                            catch { }
                        if (dr["m8"] != null && dr["m8"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m8 = Convert.ToDecimal(dr["m8"]);
                            }
                            catch { }
                        if (dr["m9"] != null && dr["m9"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m9 = Convert.ToDecimal(dr["m9"]);
                            }
                            catch { }
                        if (dr["m10"] != null && dr["m10"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m10 = Convert.ToDecimal(dr["m10"]);
                            }
                            catch { }
                        if (dr["m11"] != null && dr["m11"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m11 = Convert.ToDecimal(dr["m11"]);
                            }
                            catch { }
                        if (dr["m12"] != null && dr["m12"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m12 = Convert.ToDecimal(dr["m12"]);
                            }
                            catch { }

                        if (dr["m13"] != null && dr["m13"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m13 = Convert.ToDecimal(dr["m13"]);
                            }
                            catch { }
                        if (dr["m14"] != null && dr["m14"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m14 = Convert.ToDecimal(dr["m14"]);
                            }
                            catch { }
                        if (dr["m15"] != null && dr["m15"].ToString() != string.Empty)
                            try
                            {
                                objDetail.m15 = Convert.ToDecimal(dr["m15"]);
                            }
                            catch { }

                        if (dr["Vc_NoiBo"] != null && dr["Vc_NoiBo"].ToString() != string.Empty)
                            try
                            {
                                objDetail.Vc_NoiBo = Convert.ToDecimal(dr["Vc_NoiBo"]);
                            }
                            catch { }
                        objDetail.GhiChu = dr["GhiChu"] != null ? dr["GhiChu"].ToString() : string.Empty;
                        listDetail.Add(objDetail);
                    }
                    ValueForWorkingTimeBO objBO = new ValueForWorkingTimeBO();
                    objBO.Delete(Convert.ToInt32(txtGoodsCode.Tag));
                    objBO.Insert(objMaster, listDetail);
                    dset = objBO.GetData(objMaster.ValueForWorkingTimeMasterID);
                    dgrdData.DataSource = dset.Tables[0];
                    txtGoodsCode.Tag = objMaster.ValueForWorkingTimeMasterID;
                    MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = true;
                    btnDelete.Enabled = true;
                    btnSave.Enabled = false;
                    btnCopy.Enabled = true;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Thao tác không thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
           
            
        }
            
    

        private void btnAdd_Click(object sender, EventArgs e)
        {
            mFormAction = EnumAction.Add;
            BindDataGrid(-1);
            dgrdData.AllowAddNew = true;
            dgrdData.AllowUpdate = true;
            SetEnableButtons();
            ClearText();
            btnSelectCode.Enabled = true; cboReportType.Enabled = true;
        
        }
        #region Code Basic
        private void BindDataGrid(int iMaserID)
        {
            ValueForWorkingTimeBO objBO = new ValueForWorkingTimeBO();
            dset = objBO.GetData(iMaserID);
            dgrdData.DataSource = dset.Tables[0];

            dtbGridLayout = FormControlComponents.StoreGridLayout(dgrdData);
            dgrdData.DataSource = dset.Tables[0];
            FormControlComponents.RestoreGridLayout(dgrdData, dtbGridLayout);
            //dgrdData.AllowUpdate = true;
            ReadOnlyDataGrid();

        }
        private void ReadOnlyDataGrid()
        {
            dtbGridLayout = FormControlComponents.StoreGridLayout(dgrdData);
            if (dset.Tables.Count > 0)
            {

                dgrdData.DataSource = dset.Tables[0];

            }
            FormControlComponents.RestoreGridLayout(dgrdData, dtbGridLayout);
        }
       
        private void SetEnableButtons()
        {
            switch (mFormAction)
            {
                case EnumAction.Add:
                    //Disable Buttons
                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;

                    //Enable Buttons
                    btnSave.Enabled = true;

                    // btnIn.Enabled = false;
                    break;
                case EnumAction.Delete:
                    btnAdd.Enabled = true;
                    btnSave.Enabled = false;
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;

                    //btnIn.Enabled = false;

                    break;
                case EnumAction.Edit:
                    //Disable Buttons
                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;
                    //btnIn.Enabled = false;

                    //Enable Buttons
                    btnSave.Enabled = true;

                    break;
                case EnumAction.Default:
                    //Disable Buttons
                    btnSave.Enabled = false;
                    btnAdd.Enabled = true;
                    btnDelete.Enabled = false;
                    btnEdit.Enabled = false;

                    // btnIn.Enabled = false;
                    break;
            }
        }

        private void ClearText()
        {

            txtGoodsCode.Text = "";
            txtGoodsName.Text = "";
            txtModel.Text = "";
            txtGoodsCode.Focus();
        }

      
    

        #endregion
        private void cboReportType_SelectedValueChanged(object sender, EventArgs e)
        {
            //try
            //{
               ValueForWorkingTimeBO objBO = new ValueForWorkingTimeBO();
                //Chuyển số liệu sang bảng aa
                if (cboReportType.SelectedIndex == 0)
                {
                    objBO.RunScript(Convert.ToInt32(txtGoodsCode.Tag));
                    MessageBox.Show("Thao tác được thực hiện thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // cboReportType.SelectedValue = null;
                }
                //Run all
                if (cboReportType.SelectedIndex == 1)
                {
                    objBO.RunScript(Convert.ToInt32(txtGoodsCode.Tag));
                    objBO.RunScript2();
                    objBO.RunScript3();
                    objBO.RunScript4();
                    objBO.RunScript5();
                    objBO.RunScript6();
                    objBO.RunScript7();
                    objBO.RunScript8();
                    MessageBox.Show("Thao tác được thực hiện thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //cboReportType.SelectedIndex = -1;
                }
                //----- Import to ITM_PRODUCT
                if (cboReportType.SelectedIndex == 2)
                {
                    objBO.RunScript2();
                    MessageBox.Show("Thao tác được thực hiện thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //cboReportType.SelectedIndex = -1;
                }
                //---Import Routing%
                if (cboReportType.SelectedIndex == 3)
                {
                    objBO.RunScript3();
                    MessageBox.Show("Thao tác được thực hiện thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //cboReportType.SelectedIndex = -1;

                }
                //---Update Item co duoi LVT, VCNB bang Vat lieu phu, ProductTypeID=3
                if (cboReportType.SelectedIndex == 4)
                {
                    objBO.RunScript4();
                    MessageBox.Show("Thao tác được thực hiện thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //cboReportType.SelectedIndex = -1;
                }
                //----------- Generate BOM
                /*
                Create view v_BOM AS
                select Parent,min(parentnc) as parentnc,Parent as Component,Componentnc
                from (select p1.code Parent,p2.nc parentnc,p1.nc Componentnc from product p1, product p2
                where p1.code=p2.code and p2.nc>p1.nc) as b
                group by Parent,Componentnc
                */
                //--Insert BOM
                if (cboReportType.SelectedIndex == 5)
                {
                    objBO.RunScript5();
                    MessageBox.Show("Thao tác được thực hiện thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //cboReportType.SelectedIndex = -1;
                }
                //----- Insert BOM Nguyenvatlieu
                if (cboReportType.SelectedIndex == 6)
                {
                    objBO.RunScript6();
                    MessageBox.Show("Thao tác được thực hiện thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //cboReportType.SelectedIndex = -1;
                }
                //--- BOM THEO LevelsS
                if (cboReportType.SelectedIndex == 7)
                {
                    objBO.RunScript7();
                    MessageBox.Show("Thao tác được thực hiện thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //cboReportType.SelectedIndex = -1;
                }
                //-- Đổi chủng loại
                if (cboReportType.SelectedIndex == 8)
                {
                    objBO.RunScript8();
                    MessageBox.Show("Thao tác được thực hiện thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //cboReportType.SelectedIndex = -1;
                }
                // MessageBox.Show(cboReportType.SelectedIndex.ToString());
            //}
            //catch (Exception)
            //{
            //    MessageBox.Show("Thao tác không thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}
            
        
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            mFormAction = EnumAction.Edit;
            txtGoodsCode.Focus();
            SetEnableButtons();
            dgrdData.AllowAddNew = true;
            dgrdData.AllowUpdate = true;
            
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            txtGoodsCode.Text = "";
            txtGoodsName.Text = "";
            iCheckCopy = true;
            btnAdd.Enabled = false;
            btnEdit.Enabled = false;
            btnSave.Enabled = true;
            btnDelete.Enabled = false;
        }

        private void btnKiemtratrung_Click(object sender, EventArgs e)
        {
            ValueForWorkingTimeBO objBO = new ValueForWorkingTimeBO();
            DataSet dset = objBO.GetListTrungSP();
            if (dset != null && dset.Tables.Count > 0)
            {
                string strCode = "";
                int idem = 0;
                foreach (DataRow dr in dset.Tables[0].Rows)
                {
                    if (idem > 0 && idem < dset.Tables[0].Rows.Count - 1)
                    {
                        strCode += "," + dr["TT"].ToString();
                    }
                    else
                    {
                        strCode += dr["TT"].ToString();
                    }
                }
                MessageBox.Show("MaVTHH đã có trong hệ thống: " + strCode, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                MessageBox.Show("Không có sản phẩm nào trong hệ thống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

     
        #region Code for read Exel file
        private void btnOpenFileDlg_Click(object sender, EventArgs e)
        {
            const string METHOD_NAME = THIS + ".btnOpenFileDlg_Click()";
            try
            {
                OpenFileDialog f = new OpenFileDialog();
                f.Filter = "Excel files | *.xls";
                f.InitialDirectory = Application.ExecutablePath;

                if (f.ShowDialog() == DialogResult.OK)
                    if (f.FileName != null && f.CheckFileExists == true)
                    {
                        strExcelFilename = f.FileName;
                        txtFileName.Text = f.FileName;
                        RetrieveSheetnames();
                        if (this.cboSheetnames.Items.Count > 0)
                            cboSheetnames.SelectedIndex = 0;
                    }
            }
            catch (PCSException ex)
            {
                PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
                try
                {
                    Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
            catch (Exception ex)
            {
                PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
                try
                {
                    Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
                }
                catch
                {
                    PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
                }
            }
        }
        private void RetrieveSheetnames()
        {
            this.cboSheetnames.Items.Clear();

            if (objExcelReader != null)
            {
                objExcelReader.Dispose();
                objExcelReader = null;
            }

            objExcelReader = new ExcelReader();
            objExcelReader.ExcelFilename = strExcelFilename;
            objExcelReader.Headers = false;
            objExcelReader.MixedData = true;
            string[] sheetnames = this.objExcelReader.GetExcelSheetNames();
            this.cboSheetnames.Items.AddRange(sheetnames);
        }

        private void InitExcel(ref ExcelReader exr)
        {
            //Excel must be open
            if (exr == null)
            {
                exr = new ExcelReader();
                exr.ExcelFilename = strExcelFilename;
                exr.Headers = false;
                exr.MixedData = true;
            }
            if (dtbData == null) dtbData = new DataTable("par");
            exr.KeepConnectionOpen = true;

            //Check excel sheetname is selected
            if (this.cboSheetnames.SelectedIndex > -1)
                exr.SheetName = this.cboSheetnames.Text;
            else
                throw new PCSException(ErrorCode.MESSAGE_SELECT_SHEET, string.Empty, null);

            //Set excel sheet range
            exr.SheetRange = this.txtRange.Text;
        }
        #endregion


    }
}
